# -*- coding: utf-8 -*-
##############################################################################
#
#    OpenERP, Open Source Management Solution
#    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import xlwt
import math
from .. import format_common
from openerp.tools.translate import _
import cStringIO
from openerp.osv import osv, fields
import os, time
import base64
from babel.numbers import format_decimal
import logging
_logger = logging.getLogger(__name__)
from xlwt import *

class param_summary_project_contract_report(osv.osv_memory):
    _name = 'param.summary.project.contract.report'
    _description = 'Summary Project Contract Report'
    _columns = {
        'filter_selection': fields.selection([('all_vall','All'),('def','Default'),('input', 'Input'),('selection','Selection')],'Project Filter Selection', required=True),
        'project_default_from':fields.many2one('project.project', 'Project From', required=False),
        'project_default_to':fields.many2one('project.project', 'Project To', required=False),
        'project_input_from': fields.char('Project From', size=128),
        'project_input_to': fields.char('Project To', size=128),
        'project_name_ids' :fields.many2many('project.project', 'summary_project_contract_name_rel', 'project_name', 'project_id', 'Project'),
        'date_selection': fields.selection([('none_sel','None'),('date_sel', 'Date')],'Date Selection', required=True),
        'date_from': fields.datetime("From Date"),
        'date_to': fields.datetime("To Date"),
        'cust_filter_selection': fields.selection([('all_vall','All'),('def','Default'),('input', 'Input'),('selection','Selection')],'Customer Filter Selection', required=True), 
        'cust_name_def_from':fields.many2one('res.partner', 'Customer Name From', domain=[('customer','=',True)], required=False),
        'cust_name_def_to':fields.many2one('res.partner', 'Customer Name To', domain=[('customer','=',True)], required=False),
        'cust_name_input_from':fields.char('Customer Name From', size=128),
        'cust_name_input_to':fields.char('Customer Name To', size=128),
        'partner_ids' :fields.many2many('res.partner', 'summary_project_partner_rel', 'partner_id', 'report_id', 'Customer'),
        'curr_filter_selection': fields.selection([('all_vall','All'),('def','Default'),('input', 'Input'),('selection','Selection')],'Currency Filter Selection', required=True),
        'curr_name_def_from':fields.many2one('res.currency', 'Currency Name From', required=False),
        'curr_name_def_to':fields.many2one('res.currency', 'Currency Name To', required=False),
        'curr_name_input_from':fields.char('Currency Name From', size=128),
        'curr_name_input_to':fields.char('Currency Name To', size=128),
        'currency_ids' :fields.many2many('res.currency', 'summary_project_currency_rel', 'report_id', 'currency_id', 'Currency'),
        'sortby_ids': fields.one2many('summary.project.contract.sortby','sortby_id', 'Sort By'),
    }
    
    _defaults = {
        'filter_selection': 'all_vall', 
        'date_selection': 'none_sel',
        'cust_filter_selection': 'all_vall',
        'curr_filter_selection': 'all_vall',
    }

    def onchange_filter_selection(self, cr, uid, ids, filter_selection, context=None):
        if context is None:
            context = {}
        res = {}
        if filter_selection != 'all_vall':
             res['value'] = {'project_default_from': False, 'project_default_to': False, 'project_input_from': False, 'project_input_to': False, 'project_name_ids': False,
                                }
        return res
     
    def onchange_date_selection(self, cr, uid, ids, date_selection, context=None):
        if context is None:
            context = {}
        res = {}
        if date_selection != 'none_sel':
             res['value'] = {'date_from': False, 'date_to': False, 
                                }
        return res
    
    def onchange_filter_cust_selection(self, cr, uid, ids, filter_selection, context=None):
        if context is None:
            context = {}
        res = {}
        if filter_selection != 'all_vall':
            
             res['value'] = {'cust_name_def_from': False, 'cust_name_def_to': False, 'cust_name_input_from': False, 'cust_name_input_to': False, 'partner_ids': False,
                                }
        return res
    
    def onchange_filter_curr_selection(self, cr, uid, ids, filter_selection, context=None):
        if context is None:
            context = {}
        res = {}
        if filter_selection != 'all_vall':
            
             res['value'] = {'curr_name_def_from': False, 'curr_name_def_to': False, 'curr_name_input_from': False, 'curr_name_input_to': False, 'currency_ids': False,
                                }
        return res
    
    def _search_data(self, cr, uid, ids, data_obj, val_data, filter_selection, default_from, default_to, input_from, input_to, selection_ids, context=None):
        #Out Default Value
        data_header = ''
        data_ids = []
        #Declaration

        if context is None:
            context = {}
        
#         special_case = 'special_case' in context and context['special_case'] or False
        if filter_selection == 'all_vall':
            data_ids = data_obj.search(cr, uid, val_data, order='id ASC')
        if filter_selection == 'def':
            data_found = False
            if default_from and data_obj.browse(cr, uid, default_from) and data_obj.browse(cr, uid, default_from).name:
                default_from_header = data_obj.browse(cr, uid, default_from).name
                data_found = True
                val_data.append(('name', '>=', default_from_header))
            if default_to and data_obj.browse(cr, uid, default_to) and data_obj.browse(cr, uid, default_to).name:
                default_to_header = data_obj.browse(cr, uid, default_to).name
                data_found = True
                val_data.append(('name', '<=', default_to_header))
            if data_found:
                data_header = '"' + default_from_header + '" - "' + default_to_header + '"'
                data_ids = data_obj.search(cr, uid, val_data, order='id ASC')
        if filter_selection == 'input':
            data_found = False
            if input_from:
                data_ids_from = data_obj.search(cr, uid, [('name','=ilike',input_from + '%')], order="name", limit=1)
                if data_ids_from:
                    input_from_name = data_obj.browse(cr, uid, data_ids_from[0]).name
                    data_found = True
                    val_data.append(('name', '>=', input_from_name))
            if input_to:
                data_ids_to = data_obj.search(cr, uid, [('name','=ilike', input_to + '%')], order="name desc", limit=1)
                if data_ids_to:
                    input_to_name = data_obj.browse(cr, uid, data_ids_to[0]).name
                    data_found = True
                    val_data.append(('name', '<=', input_to_name))
            data_header = '"' + input_from + '" - "' + input_to + '"'
            if data_found:
                data_ids = data_obj.search(cr, uid, val_data, order='id ASC')
        if filter_selection == 'selection':
            if selection_ids:
                sel_ids = ''
                for sel in  data_obj.browse(cr, uid, selection_ids):
                    sel_ids += ('"%s",')%(sel.name,)

                data_header = '[' + sel_ids +']'
                data_ids = selection_ids
        return data_header, data_ids

    def _build_contexts(self, cr, uid, ids, data, context=None):
        if context is None:
            context = {}
        result = {}
        result['filter_selection'] = data['form']['filter_selection'] or False
        result['cust_filter_selection'] = data['form']['cust_filter_selection'] or False
        result['date_selection'] = data['form']['date_selection'] or False
        result['curr_filter_selection'] = data['form']['curr_filter_selection'] or False 
        result['sortby_ids'] = data['form']['sortby_ids'] or False 
        
        result['output_project_header'], result['project_ids'] = self._search_data(cr, uid, ids, self.pool.get('project.project'),
                                                                                      [('state','!=','cancelled')],
                                                                                      data['form']['filter_selection'],
                                                                                      data['form']['project_default_from'] or False,
                                                                                      data['form']['project_default_to'] or False,
                                                                                      data['form']['project_input_from'] or False,
                                                                                      data['form']['project_input_to'] or False,
                                                                                      data['form']['project_name_ids'] or False,
                                                                                      context=context)
  
        result['output_cust_header'], result['cust_ids'] = self._search_data(cr, uid, ids, self.pool.get('res.partner'),
                                                                                      [],
                                                                                      data['form']['cust_filter_selection'],
                                                                                      data['form']['cust_name_def_from'] or False,
                                                                                      data['form']['cust_name_def_to'] or False,
                                                                                      data['form']['cust_name_input_from'] or False,
                                                                                      data['form']['cust_name_input_to'] or False,
                                                                                      data['form']['partner_ids'] or False,
                                                                                      context=context)
        
        date_from = data['form']['date_from']
        date_to = data['form']['date_to']
        output_date_header = ''
        val_date = []
        if data['form']['date_selection'] == 'date_sel':
            if date_from and not date_to:
                output_date_header = 'Date Start From : %s' % (date_from,)
                val_date.append(('date_start','>=',str(date_from)))
            elif date_to and not date_from:
                output_date_header = 'Date Until : %s' % (date_to,)
                val_date.append(('date_start','<=',str(date_to))) 
            elif date_to and date_from:
                output_date_header = 'Date Start From : %s, Until: %s' % (date_from, date_to)
                val_date.append(('date_start','>=',str(date_from)))
                val_date.append(('date_start','<=',str(date_to)))

        result['output_date_header'] = output_date_header
        result['val_date'] = val_date
        
        return result
    
    def create_vat(self, cr, uid, ids, context=None):
        if context is None:
            context = {}
        datas = {'ids': context.get('active_ids', [])}
        datas['model'] = 'param.summary.project.contract.report'
        datas['form'] = self.read(cr, uid, ids)[0]
        return {
            'type': 'ir.actions.report.xml',
            'report_name': 'summary.project.contract.report_landscape',
            'datas': datas,
            'nodestroy':True,
        }
    
    def print_report(self, cr, uid, ids, context=None):
        if context is None:
            context = {}
        data = {}
        data['ids'] = context.get('active_ids', [])
        data['model'] = context.get('active_model', 'ir.ui.menu')
        data['form'] = self.read(cr, uid, ids, ['filter_selection','project_default_from','project_default_to','project_input_from','project_input_to', 'project_name_ids', \
                                                'cust_filter_selection','cust_name_def_from','cust_name_def_to','cust_name_input_from','cust_name_input_to','partner_ids', \
                                               'curr_filter_selection','curr_name_def_from','curr_name_def_to','curr_name_input_from','curr_name_input_to','currency_ids', \
                                               'date_selection', 'date_from', 'date_to', 'sortby_ids'], context=context)[0]
        for field in ['filter_selection','project_default_from','project_default_to','project_input_from','project_input_to', 'project_name_ids', \
                                                'cust_filter_selection','cust_name_def_from','cust_name_def_to','cust_name_input_from','cust_name_input_to','partner_ids', \
                                               'curr_filter_selection','curr_name_def_from','curr_name_def_to','curr_name_input_from','curr_name_input_to','currency_ids', \
                                               'date_selection', 'date_from', 'date_to', 'sortby_ids']:
            if isinstance(data['form'][field], tuple):
                data['form'][field] = data['form'][field][0]   
        used_context = self._build_contexts(cr, uid, ids, data, context=context)

        return self._get_tplines_xls(cr, uid, ids, used_context, context=context)
        
    def _get_tplines_xls(self, cr, uid, ids, form, context):

        if not ids:
            ids = data['ids']
        if not ids:
            return []
        
        user_obj = self.pool.get('res.users')
        project_project_obj = self.pool.get('project.project')
        summary_project_contract_sortby_obj = self.pool.get('summary.project.contract.sortby') 
        currency_obj = self.pool.get('res.currency')
        dp_obj = self.pool.get('decimal.precision')
        
        result         = []
        result_curr    = []
        results        = []
        val_project    = []
        dept           = []
        dept_sel       = []
        val            = []
        balance_by_cur = {}
        
        project_ids = form['project_ids']
        cust_ids = form['cust_ids'] 
        output_project_header = form['output_project_header']
        output_cust_header = form['output_cust_header']
        output_date_header = form['output_date_header']
        output_sortby_header = '' 

        if project_ids:
            val_project.append(('id','in',project_ids))
        if cust_ids:
            val_project.append(('partner_id','in',cust_ids))
        if 'val_date' in form:
            val_project += form['val_date']
        if 'sortby_ids' in form:
            summary_project_sortby_ids = summary_project_contract_sortby_obj.search(cr, uid, [('id', 'in', form['sortby_ids'])], order='seq desc')
        
        if summary_project_sortby_ids:
            for item in summary_project_contract_sortby_obj.browse(cr, uid, summary_project_sortby_ids):
                result.append({
                        'seq' : item['seq'],
                        'sort_by' : item['sort_by'],
                        })
            result = result and sorted(result, key=lambda val_res: val_res['seq']) or []               
            
            for rs in result:
                sort_name = ''
                if rs['sort_by'] == 'project_name':
                    sort_name = 'Project'
                elif rs['sort_by'] == 'cust_name':
                    sort_name = 'Customer'
                elif rs['sort_by'] == 'date_project':
                    sort_name = 'Date'
                elif rs['sort_by'] == 'currency':
                    sort_name = 'Currency'
                elif rs['sort_by'] == 'status':
                    sort_name = 'Status' 
                output_sortby_header += ('"%s",')%(sort_name,)
        
        summary_project_contract_ids = project_project_obj.search(cr, uid, val_project)
        if summary_project_contract_ids:
            
            for spc in project_project_obj.browse(cr, uid, summary_project_contract_ids):
                bill_type = ''
                cur_id_part = spc.currency_id.id
                
                bill_type = 'Actual' if spc.billing_type == 'bill' else 'Non Actual'
                
                if cur_id_part not in balance_by_cur:
                    balance_by_cur.update({cur_id_part : {
                             'quote_amt' : spc.amount_total,
                             'inv_amt' : spc.inv_amount_total,
                             'inv_amt_home' : spc.inv_amount_home_total,
                             'profit_loss' : spc.inv_amount_home_total - spc.amount_cost_total,
                             }
                        })
                else:
                    res_currency_grouping = balance_by_cur[cur_id_part].copy()
                    res_currency_grouping['quote_amt'] += spc.amount_total
                    res_currency_grouping['inv_amt'] +=  spc.inv_amount_total
                    res_currency_grouping['inv_amt_home'] += spc.inv_amount_home_total
                    res_currency_grouping['profit_loss'] += spc.inv_amount_home_total - spc.amount_cost_total
                    balance_by_cur[cur_id_part] = res_currency_grouping
                
                results.append({
                        'billing_type' : bill_type,
                        'date_spc' : spc.date_start,
                        'project_name' : spc.name,
                        'cust_name' : spc.partner_id.name,
                        'planned_normal_hours' : spc.sy_normal_qty + spc.mech_normal_qty + spc.elec_normal_qty + 
                                        spc.weld_normal_qty + spc.int_normal_qty + spc.desg_normal_qty + 
                                        spc.dept1_normal_qty + spc.dept2_normal_qty + spc.dept3_normal_qty ,
                        'planned_ot_hours' : spc.sy_ot_qty + spc.mech_ot_qty + spc.elec_ot_qty + 
                                        spc.weld_ot_qty + spc.int_ot_qty + spc.desg_ot_qty + 
                                        spc.dept1_ot_qty + spc.dept2_ot_qty + spc.dept3_ot_qty ,
                        'actual_normal_hours' : spc.sy_actual_normal_hours + spc.mech_actual_normal_hours + spc.elec_actual_normal_hours + 
                                        spc.weld_actual_normal_hours + spc.int_actual_normal_hours + spc.desg_actual_normal_hours + 
                                        spc.dept1_actual_normal_hours + spc.dept2_actual_normal_hours + spc.dept3_actual_normal_hours ,
                        'actual_ot_hours' :  spc.sy_actual_ot_hours + spc.mech_actual_ot_hours + spc.elec_actual_ot_hours + 
                                        spc.weld_actual_ot_hours + spc.int_actual_ot_hours + spc.desg_actual_ot_hours + 
                                        spc.dept1_actual_ot_hours + spc.dept2_actual_ot_hours + spc.dept3_actual_ot_hours ,
                        'curr_name' : spc.currency_id.name,
                        'quote_amt' : spc.amount_total or 0,
                        'inv_amt' : spc.inv_amount_total or 0,
                        'inv_amt_home' : spc.inv_amount_home_total or 0,
                        'profit_loss' : spc.inv_amount_home_total - spc.amount_cost_total or 0,
                        'state' : spc.state,
                    })
            
            for item in balance_by_cur.items():
                result_curr.append({
                    'cur_name' : currency_obj.browse(cr, uid, item[0]).name,
                    'quote_amt' : item[1]['quote_amt'],
                    'inv_amt' : item[1]['inv_amt'],
                    'inv_amt_home' : item[1]['inv_amt_home'],
                    'profit_loss' : item[1]['profit_loss'],
                })
            result_curr = result_curr and sorted(result_curr, key=lambda val_res: val_res['cur_name']) or []
                   
            if summary_project_sortby_ids:
                for summary_contract_sortby in summary_project_contract_sortby_obj.browse(cr, uid, summary_project_sortby_ids):
                    results = results and sorted(results, key=lambda val_res: val_res[summary_contract_sortby.sort_by]) or []               
            else:
                results = results and sorted(results, key=lambda val_res: val_res['state']) or []
                results = results and sorted(results, key=lambda val_res: val_res['curr_name']) or []
                results = results and sorted(results, key=lambda val_res: val_res['cust_name']) or []
                results = results and sorted(results, key=lambda val_res: val_res['project_name']) or []
                results = results and sorted(results, key=lambda val_res: val_res['date_spc']) or []
             
        workbook = xlwt.Workbook()
        M_header_tstyle = format_common.font_style(position='center', bold=1, border=3, fontos='black', font_height=300)
        report_tstyle = format_common.font_style(position='left', bold=1, fontos='black', font_height=190)
        report_tstyle1 = format_common.font_style(position='left', bold=1, fontos='black', font_height=180)
        header_tstyle = format_common.font_style(position='right', bold=1, fontos='black', font_height=180)
        header_tstyle_c = format_common.font_style(position='center', bold=1, border=7, fontos='black', font_height=170)
        header_tstyle_c_l_r_t_b = format_common.font_style(position='center', bold=1, border=1, fontos='black', font_height=150)
        header_tstyle_l = format_common.font_style(position='left', bold=1,border=7, fontos='black', font_height=180)
        header_tstyle_c_Top = format_common.font_style(position='center', bold=1, border=4, fontos='black', font_height=180)
        header_tstyle_c_Bottom = format_common.font_style(position='center', bold=1, border=3, fontos='black', font_height=180)
        header_tstyle_r = format_common.font_style(position='right', bold=1,  border=7,fontos='black', font_height=180)
        view_tstyle = format_common.font_style(position='left', fontos='black', font_height=180)
        view_tstyle_c = format_common.font_style(position='center', fontos='black',border=1, font_height=130)
        view_tstyle_l = format_common.font_style(position='left', fontos='black', font_height=160)
        view_tstyle_r = format_common.font_style(position='right', fontos='black', font_height=160)
        view_tstyle_r_b = format_common.font_style(position='right', bold=1, fontos='black', font_height=180)
        other_tstyle = format_common.font_style(position='left', fontos='black', font_height=180)
        other_tstyle_c = format_common.font_style(position='center', fontos='black', font_height=180)
        other_tstyle_r = format_common.font_style(position='right', fontos='black', font_height=180)
        text_tstyle = format_common.font_style(position='left', bold=1, fontos='black', font_height=170)
        text_tstyle1 = format_common.font_style(position='left', bold=1, fontos='black', font_height=220)
        text_tstyle2 = format_common.font_style(position='left', fontos='black', font_height=220)
        text_tstyle_c = format_common.font_style(position='center', bold=1, fontos='black', font_height=180)
        text_tstyle_l = format_common.font_style(position='left', bold=1, fontos='black', font_height=180)
        text_tstyle_r = format_common.font_style(position='right', bold=1, fontos='black', font_height=180)
        text_tstyle_r_closing = format_common.font_style(position='right', bold=1,border=7, fontos='black', font_height=180)
        text_tstyle_Top = format_common.font_style(position='left', bold=1, border=4, fontos='black', font_height=180)
        text_tstyle_Bottom = format_common.font_style(position='left', bold=1, border=3, fontos='black', font_height=180)
        text_tstyle_Top_r = format_common.font_style(position='right', bold=1, border=4, fontos='black', font_height=180)
        text_tstyle_Top_l = format_common.font_style(position='left', bold=1, border=4, fontos='black', font_height=180)
        text_tstyle_Top_r_r = format_common.font_style(position='right', bold=1, border=6, fontos='black', font_height=180)
        text_tstyle_Top_l_l = format_common.font_style(position='left', bold=1, border=6, fontos='black', font_height=180)
        text_tstyle_Bottom_r = format_common.font_style(position='right', bold=1, border=3, fontos='black', font_height=180)
        text_tstyle_TopBottom = format_common.font_style(position='left', bold=1, border=2, fontos='black', font_height=180)
        text_tstyle_TopBottom_r = format_common.font_style(position='right', bold=1, border=2, fontos='black', font_height=180)
        
        
         ## decimat format number
        dp_data = {}
        decimal_format = easyxf(num_format_str = '0.000000')
        dp_ids = dp_obj.search(cr, uid, [])
        print dp_ids
        for dp_id in dp_obj.browse(cr, uid, dp_ids, context=None) :
            dp_data[dp_id.name] = dp_id.digits
        
        #get data decimal precision by name 
        dp_account = dp_data['Account']
        dp_product_price = dp_data['Product Price']
        dp_product_uom = dp_data['Product Unit of Measure']
        
        #digit by account
        digits = int(math.pow(10, dp_account))
        digit_output = '#,##0.' + str(digits)[1:]

        currency_format = easyxf(num_format_str = digit_output)
        
        credit_limit_format = easyxf('font: bold 1; border: top thin')
        credit_limit_format.num_format_str = digit_output
        
        currency_ttl_format = easyxf('font: bold 1')
        currency_ttl_format.num_format_str = digit_output
        
        total_ttl_format_closing = easyxf('font: bold 1; border: top thick, bottom thick, left thick, right thick')
        total_ttl_format_closing.num_format_str = digit_output

        currency_ttl_format_tlrb_view = easyxf('border: top thin, bottom thin, left thin, right thin')
        currency_ttl_format_tlrb_view.num_format_str = digit_output
        
        currency_ttl_format_tlrb = easyxf('font: bold 1; border: top thick, bottom thick, left thick, right thick')
        currency_ttl_format_tlrb.num_format_str = digit_output
        
        
        #digit by unit price
        digits_up = int(math.pow(10, dp_product_price))
        digit_output_up = '#,##0.' + str(digits_up)[1:]

        unit_price_format = easyxf(num_format_str = digit_output_up)
        
        unit_price_ttl_format_tlrb_view = easyxf('border: top thin, bottom thin, left thin, right thin; font: name Verdana; font: height 130')
        unit_price_ttl_format_tlrb_view.num_format_str = digit_output_up
        
        #digit by unit of measure
        digits_uom = int(math.pow(10, dp_product_uom))
        digit_output_uom = '#,##0.' + str(digits_uom)[1:]

        unit_of_measure_format = easyxf(num_format_str = digit_output_uom)
        
        unit_of_measure_ttl_format_tlrb_view = easyxf('border: top thin, bottom thin, left thin, right thin')
        unit_of_measure_ttl_format_tlrb_view.num_format_str = digit_output_uom
        
        #### decimat format number
        
        ####################
        sheet = workbook.add_sheet('Summary Contract Report XLS')
        sheet.row(0).height = 350
        row=0
        
        company_name = user_obj.browse(cr, uid, uid).company_id.name
        sheet.write_merge(row, row, 0, 13, company_name, report_tstyle1)
        
        row+=1
        sheet.write_merge(row, row, 0, 13, 'Summary Project Contract Report', report_tstyle1)
        
        user_ids = user_obj.search(cr, uid, [('id','=',uid)])
        if user_ids :
            tz = user_obj.browse(cr, uid, user_ids[0])
            tz_name = tz.tz
            user_name = tz.name
            
        os.environ['TZ'] = tz_name
        time.tzset()
        
        row+=1
        sheet.write_merge(row, row, 0, 2, 'Printed date : ' + time.strftime("%Y/%m/%d") + '  Time : '+ time.strftime("%H:%M:%S"), view_tstyle)
        sheet.write_merge(row, row, 9, 13, 'Printed by : ' + user_name, view_tstyle)
        
        if form['filter_selection'] != 'all_vall' :
            row += 1
            sheet.write_merge(row, row, 0, 13, '   Project : ' + output_project_header, text_tstyle)
        
        if form['cust_filter_selection'] != 'all_vall':
            row += 1
            sheet.write_merge(row, row, 0, 13, '   Customer : ' + output_cust_header, text_tstyle)
        
        if form['date_selection'] != 'none_sel':
            row += 1
            sheet.write_merge(row, row, 0, 13, '   ' + output_date_header, text_tstyle)
        
        if form['curr_filter_selection'] != 'all_vall':
            row += 1
            sheet.write_merge(row, row, 0, 13, '   Currency : ' , text_tstyle)
         
        if form['sortby_ids']:
            row += 1
            sheet.write_merge(row, row, 0, 13, '   Sort By : ' + output_sortby_header, text_tstyle)
        
        row+=1
        sheet.write(row, 0, '', view_tstyle)
        
        row+=1
        sheet.row(row).height = 600
        sheet.write(row, 0, 'Order Date', header_tstyle_c_l_r_t_b)
        sheet.write(row, 1, 'Project Name', header_tstyle_c_l_r_t_b)
        sheet.write(row, 2, 'Customer', header_tstyle_c_l_r_t_b)
        sheet.write(row, 3, 'Billing Type', header_tstyle_c_l_r_t_b)
        sheet.write(row, 4, 'Planned Normal Hour', header_tstyle_c_l_r_t_b)
        sheet.write(row, 5, 'Planned OT Hour', header_tstyle_c_l_r_t_b)
        sheet.write(row, 6, 'Actual Normal Hour', header_tstyle_c_l_r_t_b)
        sheet.write(row, 7, 'Actual OT Hour', header_tstyle_c_l_r_t_b)
        sheet.write(row, 8, 'CCY', header_tstyle_c_l_r_t_b)
        sheet.write(row, 9, 'Quote Amt', header_tstyle_c_l_r_t_b)
        sheet.write(row, 10, 'Inv Amt', header_tstyle_c_l_r_t_b)
        sheet.write(row, 11, 'Inv Amt Home', header_tstyle_c_l_r_t_b)
        sheet.write(row, 12, 'Profit/loss', header_tstyle_c_l_r_t_b)
        sheet.write(row, 13, 'Status', header_tstyle_c_l_r_t_b)
         
        sheet.col(0).width = 256 * 14
        sheet.col(1).width = 256 * 18
        sheet.col(2).width = 256 * 18
        sheet.col(3).width = 256 * 10
        sheet.col(4).width = 256 * 10
        sheet.col(5).width = 256 * 8
        sheet.col(6).width = 256 * 8
        sheet.col(7).width = 256 * 8
        sheet.col(8).width = 256 * 10
        sheet.col(9).width = 256 * 8
        sheet.col(10).width = 256 * 8
        sheet.col(11).width = 256 * 8
        sheet.col(12).width = 256 * 10
        sheet.col(13).width = 256 * 7
        
        for rs1 in results:
            row += 1
            sheet.write(row, 0, str(rs1['date_spc']), unit_price_ttl_format_tlrb_view)
            sheet.write(row, 1, str(rs1['project_name']), unit_price_ttl_format_tlrb_view)
            sheet.write(row, 2, str(rs1['cust_name']), unit_price_ttl_format_tlrb_view)
            sheet.write(row, 3, str(rs1['billing_type']), unit_price_ttl_format_tlrb_view)
            sheet.write(row, 4, rs1['planned_normal_hours'], unit_price_ttl_format_tlrb_view) 
            sheet.write(row, 5, rs1['planned_ot_hours'], unit_price_ttl_format_tlrb_view)
            sheet.write(row, 6, rs1['actual_normal_hours'], unit_price_ttl_format_tlrb_view) 
            sheet.write(row, 7, rs1['actual_ot_hours'], unit_price_ttl_format_tlrb_view)
            sheet.write(row, 8, str(rs1['curr_name']), view_tstyle_c)
            sheet.write(row, 9, rs1['quote_amt'], unit_price_ttl_format_tlrb_view) 
            sheet.write(row, 10, rs1['inv_amt'], unit_price_ttl_format_tlrb_view) 
            sheet.write(row, 11, rs1['inv_amt_home'], unit_price_ttl_format_tlrb_view) 
            sheet.write(row, 12, rs1['profit_loss'], unit_price_ttl_format_tlrb_view) 
            sheet.write(row, 13, str(rs1['state']), unit_price_ttl_format_tlrb_view) 
        
        for rs2 in result_curr:
            row += 1
            sheet.write(row, 7, 'TOTAL', unit_price_ttl_format_tlrb_view)
            sheet.write(row, 8, str(rs2['cur_name']), view_tstyle_c)
            sheet.write(row, 9, rs2['quote_amt'], unit_price_ttl_format_tlrb_view) 
            sheet.write(row, 10, rs2['inv_amt'], unit_price_ttl_format_tlrb_view) 
            sheet.write(row, 11, rs2['inv_amt_home'], unit_price_ttl_format_tlrb_view) 
            sheet.write(row, 12, rs2['profit_loss'], unit_price_ttl_format_tlrb_view)  
            
        row += 1
        sheet.row(row).height = 100
        sheet.write_merge(row, row, 0, 13, '', report_tstyle1)
           
        row += 1
        sheet.write_merge(row, row, 0, 13, 'End of Report', text_tstyle_Top_l) 
        
        stream = cStringIO.StringIO()
        workbook.save(stream)
            
        cr.execute(""" DELETE FROM output""")
        attach_id = self.pool.get('output').create(cr, uid, {'name':'Summary Project Contract Report.xls', 'xls_output':base64.encodestring(stream.getvalue())})
        return {
                'name': _('Notification'),
                'context': context,
                'view_type': 'form',
                'view_mode': 'form',
                'res_model': 'output',
                'res_id':attach_id,
                'type': 'ir.actions.act_window',
                'target':'new'
                }

class summary_project_contract_sortby(osv.osv_memory):
    
    _name = "summary.project.contract.sortby"
    
    _columns = {
        'sortby_id': fields.many2one('param.summary.project.contract.report', 'Sort By', required=True, ondelete='cascade'),
        'seq': fields.integer('Sequence', required=True),
        'sort_by': fields.selection([('date_project', 'Date'),('project_name','Project'),('cust_name', 'Customer'),('currency', 'Currency'), ('status', 'Status')],'Sort by', required=True),
    }
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
